package controllers

import (
	"bitbucket.org/alanwhen/infant-experience-class/enums"
	"bitbucket.org/alanwhen/infant-experience-class/models"
	"fmt"
	"github.com/astaxie/beego"
	"golang.org/x/crypto/bcrypt"
	"strings"
	"time"
)

type HomeController struct {
	BaseController
}

func (this *HomeController) Index() {
	this.Data["pageTitle"] = "首页"
	this.ActiveSidebarUrl()
	this.checkLogin()
	this.setTpl()
}

func (this *HomeController) Page404() {
	this.setTpl("home/page404", "shared/layout_base")
}

func (this *HomeController) Error() {
	this.Data["error"] = this.GetString(":error")
	this.setTpl("home/error", "shared/layout_pullbox", "")
}

func (this *HomeController) Login() {
	this.Data["pageTitle"] = beego.AppConfig.String("site.app") + beego.AppConfig.String("site.name") + " - 登陆"
	this.Data["siteVersion"] = beego.AppConfig.String("site.version")

	if this.Input().Get("url") != "" {
		this.Data["url"] = "?url=" + this.Input().Get("url")
	}

	this.setTpl("home/login", "shared/layout_base")
}

//退出
func (this *HomeController) Logout() {
	user := models.SysUser{}
	this.SetSession("sys_user", user)
	this.pageLogin()
}

//登陆
func (this *HomeController) DoLogin() {
	remoteAddr := this.Ctx.Request.RemoteAddr
	address := strings.Split(remoteAddr, "::1")
	if len(address) > 1 {
		remoteAddr = "localhost"
	}
	//
	username := strings.TrimSpace(this.GetString("UserName"))
	password := strings.TrimSpace(this.GetString("Password"))

	if err := models.LoginTraceAdd(username, remoteAddr, time.Now()); err != nil {
		beego.Error("LoginTraceAdd error.")
	}
	beego.Info(fmt.Sprintf("login: %s IP: %s", username, remoteAddr))

	if len(username) == 0 || len(password) == 0 {
		this.jsonResult(enums.JRCodeFailed, "用户名和密码不正确", "")
	}
	//hash, error := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	//if error != nil {
	//	this.jsonResult(enums.JRCodeFailed, "输出密码是", "")
	//}
	user, err := models.SysUserOneByUserName(username)
	if user != nil && err == nil {
		if user.Status == enums.Disabled {
			this.jsonResult(enums.JRCodeFailed, "用户被禁用，请联系管理员", "")
		}

		err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
		if err != nil {
			this.jsonResult(enums.JRCodeFailed, "用户名或密码错误", "")
		}

		//保存用户信息到session
		this.setSysUser2Session(user.Id)

		obj := make(map[string]string)
		if this.Input().Get("url") != "" {
			obj["redirect"] = this.Input().Get("url")
		}
		//获取用户信息
		this.jsonResult(enums.JRCodeSuccess, "登录成功", obj)
	} else {
		this.jsonResult(enums.JRCodeFailed, "用户名或者密码错误", "")
	}
}
